package LogServer.dao

import LogServer.constants.PropertiesMongo
import com.mongodb.{DBCollection, ServerAddress}
import com.mongodb.casbah.{MongoClient, MongoCredential, MongoDB}

/**
  * Created by root on 17-2-14.
  */
// 私有构造方法
class MongoConnector private {

}

// 伴生对象，与类共享名字，可以访问类的私有属性和方法
object MongoConnector{
   var db: Option[MongoDB] = None
  /**
    * 创建Mongo数据库连接
    * @param propertiesMongoObject
    * @return MongoDB Object
    */
  def getConnection(propertiesMongoObject: PropertiesMongo): MongoDB = {
    //Mongo Client
    val url = propertiesMongoObject.mongoUrl
    val server = new ServerAddress(url,27017)
    val dbName = propertiesMongoObject.mongoDbName
    val user = propertiesMongoObject.mongoUser
    val pwd = propertiesMongoObject.mongoPwd
    val credentials = MongoCredential.createMongoCRCredential(dbName,user,pwd.toArray)
    val mongoClient = MongoClient(server,List(credentials))
    this.db = Some(mongoClient(dbName))
    mongoClient(dbName)
  }

  /**
    * 创建Mongo数据库连接
    * @param propertiesMongoObject
    * @param collectionName
    * @return
    */
  def getConnection(propertiesMongoObject: PropertiesMongo, collectionName: String): DBCollection = {
    this.db match {
      case Some(s) => s.getCollection(collectionName)
      case None => {
        val db = getConnection(propertiesMongoObject)
        this.db = Some(db)
        val collection = db.getCollection(collectionName)
        collection
      }
    }
  }
}
